<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class AuthRule extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $rule=model('AuthRule')->cateSort();
        $this->assign('rule',$rule);
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {   
        $rule=model('AuthRule')->cateSort();
        $this->assign('rule',$rule);
        return view();
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $add=db('AuthRule')->insert($data);
            if ($add) {
                $this->success('规则添加成功','index');
            }
            $this->error('规则添加失败');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {   
        if (request()->isPost()) {
            $data=input('post.');
            $edit=db('AuthRule')->where('id',$data['id'])->update($data);
            if ($edit) {
               $this->success('规则编辑成功','index');
            }
            $this->error('规则编辑失败');
        }
        $res=db('AuthRule')->find($id);
        $rule=model('AuthRule')->cateSort();
        $this->assign([
            'res' =>$res,
            'rule'=>$rule,
        ]);
       return view();
    }

    

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (request()->isAjax()) {
            $res=model('AuthRule')->getChildIds($id);
            foreach ($res as $k => $v) {
                $rules=db('AuthRule')->delete($v);
            }
            if ($rules) {
                return json(['code'=>1,'删除成功']);
            }
            return json(['code'=>2,'删除失败']);
        }
        
    }
}
